package com.eptok.weixin.util;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Random;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class HuaBan {

	public static String q = "http://image.baidu.com/search/avatarjson?tn=resultjsonavatarnew&ie=utf-8&word="
			+ "keyword"
			+ "&cg=girl&pn=random&rn=1&itg=0&z=0&fr=&lm=-1&ic=0&s=0&st=-1&gsm=12c000000012c";
	
	public static String q2 = "http://huaban.com/search/?q=keyword&iu7s81z5&page=random&per_page=1&wfl=1";
	
	public static void main(String[] args) {
		getImgRoundBD("清纯美女");
		getImgRoundHB("清纯美女");
	}
	
	public static String getImgRoundBD(String keyword)
	{
		String s = "";
		try {
			String url = q;
			keyword = URLEncoder.encode(keyword,"UTF-8");
			url = url.replace("keyword", keyword);
			String r = getRandom()+"";
			url = url.replace("random", r);
			
			HttpClient client = new HttpClient();
			GetMethod get = new GetMethod(url);
			get.setRequestHeader("X-Requested-With","XMLHttpRequest");
			get.setRequestHeader("Accept","application/json");
			
			client.executeMethod(get);
			s = new String(get.getResponseBodyAsString());
			
			JSONObject json = JSONObject.fromObject(s);
			JSONArray imgs = json.getJSONArray("imgs");
			JSONObject img0 =  imgs.getJSONObject(0);
			System.out.println("从百度取到的图片（随机数："+r+"，关键字："+URLDecoder.decode(keyword,"UTF-8")+"）地址："+img0.get("objURL"));
			return img0.getString("objURL");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	
	public static String getImgRoundHB(String keyword)
	{
		String s = "";
		try {
			String url = q2;
			keyword = URLEncoder.encode(keyword,"UTF-8");
			url = url.replace("keyword", keyword);
			String r = getRandom()+"";
			url = url.replace("random", r);
			HttpClient client = new HttpClient();
			GetMethod get = new GetMethod(url);
			get.setRequestHeader("X-Requested-With","XMLHttpRequest");
			get.setRequestHeader("Accept","application/json");
			
			client.executeMethod(get);
			s = new String(get.getResponseBodyAsString());
			
			JSONObject json = JSONObject.fromObject(s);
			JSONArray imgs = json.getJSONArray("pins");
			JSONObject img0 = imgs.getJSONObject(0);
			JSONObject img0File = img0.getJSONObject("file");
			String key = img0File.getString("key");
			String urlr = "http://img.hb.aicdn.com/"+key;
			System.out.println("从花瓣网取到的图片（（随机数："+r+"关键字："+URLDecoder.decode(keyword,"UTF-8")+"）地址："+urlr);
			return urlr;
		} catch (HttpException e) {
			return "";
		} catch (IOException e) {
			return "";
		}
	}
	
	public static int getRandom()
	{
		int max=1000;
		int min=1;
		Random random = new Random();
		int s = random.nextInt(max)%(max-min+1) + min;
		return s;
	}
}
